﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace reportsDesktop
{
    public partial class frmMain : Form
    {
        Point oldPoint;
        bool mouseDown;

        bool countSet = false;
        int count = 0;//联合使用，防止因多个ifram导致DocumentCompleted执行多次



        NetConnectState connect = new NetConnectState();

        frmSetting set;


        //form movie
        [DllImport("user32")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        const int AW_HOR_POSITIVE = 0x0001;
        const int AW_HOR_NEGATIVE = 0x0002;
        const int AW_VER_POSITIVE = 0x0004;
        const int AW_VER_NEGATIVE = 0x0008;
        const int AW_CENTER = 0x0010;
        const int AW_HIDE = 0x10000;
        const int AW_ACTIVATE = 0x20000;
        const int AW_SLIDE = 0x40000;
        const int AW_BLEND = 0x80000;

        public frmMain()
        {
            InitializeComponent();
            tableLayoutPanel2.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel2, true, null);
            tableLayoutPanel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel1, true, null);
            tableLayoutPanel3.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel3, true, null);
            tableLayoutPanel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel1, true, null);
            panel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(panel1, true, null);

            this.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(this, true, null);
            webBrowser1.ScriptErrorsSuppressed = true;
        }

        private void tableLayoutPanel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                oldPoint = e.Location;
                mouseDown = true;
            }
        }

        private void tableLayoutPanel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {
                this.Left += (e.X - oldPoint.X);
                this.Top += (e.Y - oldPoint.Y);
            }
        }

        private void tableLayoutPanel2_MouseUp(object sender, MouseEventArgs e)
        {
            mouseDown = false;
        }



        private void frmMain_Paint(object sender, PaintEventArgs e)
        {
            if (!(this.WindowState == FormWindowState.Maximized))
                //RoundFormPainter.Paint(sender);
                RoundFormPainter.SetWindowRegion(sender);
            else
                this.Region = null;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void btnMax_Click(object sender, EventArgs e)
        {
            ResizeForm();
        }

        private void ResizeForm()
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;

                tableLayoutPanel2.Width = this.Width;
                TableLayoutColumnStyleCollection styles = this.tableLayoutPanel2.ColumnStyles;
                styles[2].SizeType = SizeType.Absolute;
                styles[2].Width = 367;

                TableLayoutColumnStyleCollection styles2 = this.tableLayoutPanel1.ColumnStyles;
                styles2[2].SizeType = SizeType.Absolute;
                styles2[2].Width = 330;

                pnlBody.Width = 800;
                tableLayoutPanel1.Width = 800;
                pnlBody.Height = 415;
                tableLayoutPanel1.Location = new Point(0, 475);

                btnMax.Bitmap = Properties.Resources.max2;

                SetMargin();

            }
            else
            {
                this.MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
                this.WindowState = FormWindowState.Maximized;
                tableLayoutPanel2.Width = Screen.PrimaryScreen.WorkingArea.Width;

                TableLayoutColumnStyleCollection styles = this.tableLayoutPanel2.ColumnStyles;
                styles[2].SizeType = SizeType.Absolute;
                styles[2].Width = Screen.PrimaryScreen.WorkingArea.Width - 423;

                TableLayoutColumnStyleCollection styles2 = this.tableLayoutPanel1.ColumnStyles;
                styles2[2].SizeType = SizeType.Absolute;
                styles2[2].Width = Screen.PrimaryScreen.WorkingArea.Width - 470;

                pnlBody.Width = tableLayoutPanel2.Width;
                tableLayoutPanel1.Width = tableLayoutPanel2.Width;
                pnlBody.Height = Screen.PrimaryScreen.WorkingArea.Height - 90;
                tableLayoutPanel1.Location = new Point(0, 60 + pnlBody.Height);

                btnMax.Bitmap = Properties.Resources.Max3;

                ClearMargin();
            }
        }

        private void ClearMargin()
        {
            btnMin.Margin = new Padding(0);
            btnMax.Margin = new Padding(0);
            btnClose.Margin = new Padding(0);
            btnClose.Width = 33;
        }
        private void SetMargin()
        {
            btnMin.Margin = new Padding(0, 2, 0, 0);
            btnMax.Margin = new Padding(0, 2, 0, 0);
            btnClose.Margin = new Padding(0, 2, 3, 0);
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visible == true)
                    this.Visible = false;
                else
                {
                    this.Visible = true;
                }
            }
        }

        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            AnimateWindow(this.Handle, 200, AW_CENTER | AW_ACTIVATE);

            UpdateCmbUrl();

            if (Properties.Settings.Default.showInstr)
            {
                webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted2);
                webBrowser1.Navigate("about:blank");
            }
            else
            {
                webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
                btnHome_Click(null, null);
            }

            set = frmSetting.CreateInstence(this);
        }

        private void ShowInstr()
        {
            webBrowser1.Document.Body.Style = "background-color:#FFD1A4;padding:0;text-align:center;margin:20px 0 20px 0; font-size:14px;";
            string instr = "<div style='width:70%;text-align:left'><p style='text-align:center;font-size:24px;'>景风无线WLAN2.0使用说明</p><p style='font-size:11px;text-indent:2em;'>前言：本软件仅作为WLAN或者wifi登陆使用，不包括破解或解密功能。适用于购买了类似中国移动的WLAN服务，使用时需要在浏览器输入用户名密码，而能关闭浏览器的情况。软件运行需要 .net 4.0 环境。</p>功能说明：<p style='text-indent:2em;'>1.使用软件登陆WLAN后可以放心大胆的关闭浏览器，软件主窗口关闭后会最小化到桌面右下角系统托盘。</p><p style='text-indent:2em;'>2.记住用户名及密码，不用每次都重复输入；此基础上可以进行自动登陆，更快联通网络。</p><p style='text-indent:2em;'>3.联网计时，为购买包时服务的用户更清楚知道剩余可上网时长，不再月底空对网兴叹。</p><p style='text-indent:2em;'>4.关闭显示器功能，无人时或者下载待机时将显示器关闭，方便一些不能直接用按键关闭显示器的用户，省电、节能、环保。</p>使用说明：<p style='text-indent:2em;'>1.获取WLAN的登陆地址。连接WLAN而未联网时，打开百度后跳转的地址就是登陆地址。</p><p style='text-indent:2em;'>2.打开WLAN的登陆地址（在设置中将登陆地址设为首页更方便哦），不需使用软件提供的记住用户名密码功能的用户，直接在打开页面中输入用户名密码即可，关闭本窗口后软件即最小化到系统托盘，就可网络畅爽了。需要使用软件提供的记住用户名密码功能的用户，请看第3步。</p><p style='text-indent:2em;'>3.打开登陆页面后，在右下角系统托盘中右键打开软件的设置选项，设置窗口中点击[刷新列表]，选择'用户方式'、'密码方式'，在文本框中输入用户名密码，若登陆页面中的用户名密码也同时自动填入，说明选择正确，未自动填入则需选择正确的'用户方式'、'密码方式'。</p><p style='text-indent:2em;'>4.若需使用自动登陆功能，在第3步的基础上选择正确的'登陆方式'后，勾选自动登陆即可。不清楚选择的'登陆方式'是否正确时，可以点击[测试登陆]按钮，以验证选择。</p><p style='text-indent:2em;'>5.时长统计功能使用方法一目了然，不再赘余。</p>感谢网友世态悲凉、素手出锋芒、巡鹰2000提供的测试和建议。<br />如有疑问或建议，可加入免费技术支持QQ群：260787206，或发送邮件至350682272@qq.com进行反馈。<br />时间预警、定时下线、定时关机等更多功能欢迎关注下版。<br />软件下载及更新地址：<a style='color:black' target='_blank' href='http://www.duote.com/soft/13431.html'>http://www.duote.com/soft/13431.html</a><p style='text-align:right;'>by景风</p></div>";
            webBrowser1.Document.Body.InnerHtml = instr;
        }


        private void tableLayoutPanel2_DoubleClick(object sender, EventArgs e)
        {
            ResizeForm();
        }
        #region 关闭显示器
        public const uint WM_SYSCOMMAND = 0x0112;
        public const uint SC_MONITORPOWER = 0xF170;
        [DllImport("user32")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam);

        private void 关闭显示器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CloseLCD(sender, e);//关闭显示器
        }

        public void CloseLCD(object sender, EventArgs e)
        {
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, 2);    // 2 为关闭显示器， －1则打开显示器 
        }
        #endregion
        #region 注销、关闭、重启计算机
        [DllImport("user32.dll", EntryPoint = "ExitWindowsEx", CharSet = CharSet.Ansi)]
        //ExitWindowsEx 函数
        private static extern int ExitWindowsEx(int uFlags, int dwReserved);
        public void zhuxiao() //注销
        {
            ExitWindowsEx(0, 0);
        }

        public void guanji()//关机
        {
            try
            {
                Process.Start("Shutdown.exe", " -s -t 0");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void chongqi()//重启
        {
            try
            {
                Process.Start("shutdown.exe", " -r -t 0");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            set = frmSetting.CreateInstence(this);
            set.Show();

        }

        private void cmbUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
                webBrowser1.Navigate(cmbUrl.Text);
        }
        //显示使用说明
        private void webBrowser1_DocumentCompleted2(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted2);
            ShowInstr();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.Document.GetElementsByTagName("iframe").Count > 0)
            {
                if (countSet == false)
                {
                    countSet = true;
                    count++;
                }
                else
                {
                    if (count != webBrowser1.Document.GetElementsByTagName("iframe").Count)
                    {
                        count++;
                        return;
                    }
                    else
                        AfferCompleted();

                }

            }
            else
                AfferCompleted();
        }

        private void AfferCompleted()
        {

            count = 0;
            countSet = false;



            if (!connect.ConnectTest() && Properties.Settings.Default.remember && webBrowser1.Url.ToString() == Properties.Settings.Default.formUrl)
            {
                string error = "产生错误，请检查设置,错误如下:";

                webBrowser1.DocumentText = Properties.Settings.Default.form;

                //todo:登陆处理
                try
                {
                    if (Properties.Settings.Default.autoLogin == true)
                    {
                        webBrowser1.Document.GetElementById(Properties.Settings.Default.loginControl).InvokeMember("click");
                    }
                }
                catch (Exception ee)
                {
                    error += "\n自动登陆出错！";
                }
                if (error != "产生错误，请检查设置,错误如下:")
                    MessageBox.Show(error);
            }
            TimeCount();

        }

        private void TimeCount()
        {
            if (connect.ConnectTest() && Properties.Settings.Default.useTimeCount == true)
            {
                timer1.Start();
            }
        }

        private void cmbUrl_SelectedIndexChanged(object sender, EventArgs e)
        {
            webBrowser1.Navigate(cmbUrl.Text);
        }

        private void btnHome_Click(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.home != "")
            {
                cmbUrl.Text = Properties.Settings.Default.home;
                webBrowser1.Navigate(Properties.Settings.Default.home);
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();
        }
        public void UpdateCmbUrl()
        {
            cmbUrl.Items.Clear();
            if (Properties.Settings.Default.home.Trim() != "")
                cmbUrl.Items.Add(Properties.Settings.Default.home.Trim());
            if (Properties.Settings.Default.url1.Trim() != "")
                cmbUrl.Items.Add(Properties.Settings.Default.url1.Trim());
            if (Properties.Settings.Default.url2.Trim() != "")
                cmbUrl.Items.Add(Properties.Settings.Default.url2.Trim());
            if (Properties.Settings.Default.url3.Trim() != "")
                cmbUrl.Items.Add(Properties.Settings.Default.url3.Trim());
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            cmbUrl.Text = webBrowser1.Url.ToString();
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (connect.ConnectTest() && Properties.Settings.Default.useTimeCount == true)
            {
                int hour = Properties.Settings.Default.usedHour;
                int min = Properties.Settings.Default.usedMin;
                min++;
                if (min == 60)
                {
                    min = 0;
                    hour++;
                }
                Properties.Settings.Default.usedMin = min;
                Properties.Settings.Default.usedHour = hour;
                Properties.Settings.Default.Save();
                set.txtUsedHour.Text = hour.ToString();
                set.txtUsedMin.Text = min.ToString();
            }
            if (Properties.Settings.Default.useTimeCount == false)
                timer1.Stop();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            webBrowser1.GoForward();
        }

        private void 打开窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
        }

        private void frmMain_Deactivate(object sender, EventArgs e)
        {
            this.Visible = false;
        }


    }
}
